<?
#####################################################
#  COPYRIGHT NOTICE
#####################################################
# In the following statements, the term "this 
# program" refers to all files associated with the
# execution and distribution of Adtrackz.
#
# This Program is Copyright 2004 Jonah Klimack.
# All Rights Reserved. 
#
# Selling the code for this program, modifying 
# and/or redistributing the code for this program
# in part or in whole over the Internet or in any 
# other medium is expressly forbidden. Violators
# will be prosecuted to the fullest extent of the law
# Copyright and header information may not be
# modified.
#
# This program is distributed "as is" and without 
# warranty of any kind, either express or implied.
# In no event shall the liability of Jonah Klimack 
# for any damages, losses and/or causes of 
# action exceed the total amount paid by the 
# user for this software.		
#####################################################
# DO NOT MODIFY ANYTHING IN THIS FILE
#####################################################

require "header.php";	

//sets starting values if loading page from menu
if (!$group && !$status && !$timeperiod && !$purpose) //clicking on stats in menu
{
	$starting_pref = mysql_fetch_row(mysql_query("select purpose,group1,status,timeperiod from adtrackz_preferences"));
	$purpose = $starting_pref[0];
	$group = $starting_pref[1];
	$status = $starting_pref[2];
	$timeperiod = $starting_pref[3];
	$submit_top = "yes";
}
else //button was clicked, so see if group is default
{
	if (!$group)
		$group = "default";
}

?>
<p class="small" align="left">
Campaigns > Statistics
</p>
<p class="heading">
Your Statistics
</p>
<p align=right>
<a href="preferences.php">Change Preferences...</a>
</p>


<form action="stats.php" method="post">
<!--MAIN CONTROLS-->
<table width="580" border="0" cellpadding="0" cellspacing="0" align="center" valign="center">
	<tr>
		<td>Purpose</td>
		<td>Group</td>
		<td>Status</td>
		<td>Time Period</td>
		<td>&nbsp;</td>
	</tr>
	<tr>
		<td>
			<?
				if ($purpose == "all purposes")
					$all_purposes_selected = "selected";
				elseif ($purpose == "clicks")
					$clicks_selected = "selected";
				elseif ($purpose == "actions")
					$actions_selected = "selected";
				elseif ($purpose == "sales")
					$sales_selected = "selected";
				elseif ($purpose == "all")
					$all_selected = "selected";
				elseif ($purpose == "affiliate")
					$affiliate_selected = "selected";
			?>
			<select name="purpose" class="small">
			<option value="all purposes" <?=$all_purposes_selected?>>All</option>
			<option value="clicks" <?=$clicks_selected?>>Clicks Only</option>
			<option value="actions" <?=$actions_selected?>>Clicks & Actions</option>
			<option value="sales" <?=$sales_selected?>>Clicks & Sales</option>
			<option value="all" <?=$all_selected?>>Clicks, Actions & Sales</option>
			<option value="affiliate" <?=$affiliate_selected?>>Affiliate Link</option>
			</select>
		</td>
		<td>
			<select name="group" class="small">
			<?
				if ($group == "all")
					echo "<option value=all selected>All</option>";
				else
					echo "<option value=all>All</option>";
				if ($group == "default")
					echo "<option value=default selected>- default -</option>";
				else
					echo "<option value=default>- default -</option>";
				$groups = mysql_query("select * from adtrackz_groups order by groupname asc");
				while($group1 = mysql_fetch_row($groups))
				{
					if ($group == $group1[0])
						echo "<option value=$group1[0] selected>$group1[1]</option>";
					else
						echo "<option value=$group1[0]>$group1[1]</option>";
				}
			?>
			</select>
		</td>
		<td>
			<?
				if ($status == "all")
					$s_all_selected = "selected";
				elseif ($status == "active")
					$s_active_selected = "selected";
				elseif ($status == "ended")
					$s_ended_selected = "selected";
				elseif ($status == "pending")
					$s_pending_selected = "selected";
			?>
			<select name="status" class="small">
			<option value="all" <?=$s_all_selected?>>All</option>
			<option value="pending" <?=$s_pending_selected?>>pending</option>
			<option value="active" <?=$s_active_selected?>>active</option>
			<option value="ended" <?=$s_ended_selected?>>ended</option>
			</select> 
		</td>
		<td>
			<?
				if ($timeperiod == "all")
					$tp_all_selected = "selected";
				elseif ($timeperiod == "today")
					$tp_today_selected = "selected";
				elseif ($timeperiod == "yesterday")
					$tp_yesterday_selected = "selected";
				elseif ($timeperiod == "thisweek")
					$tp_thisweek_selected = "selected";
				elseif ($timeperiod == "lastweek")
					$tp_lastweek_selected = "selected";
				elseif ($timeperiod == "thismonth")
					$tp_thismonth_selected = "selected";
				elseif ($timeperiod == "lastmonth")
					$tp_lastmonth_selected = "selected";
				elseif ($timeperiod == "thisyear")
					$tp_thisyear_selected = "selected";
				elseif ($timeperiod == "lastyear")
					$tp_lastyear_selected = "selected";
			?>
			<select name="timeperiod" class="small">
			<option value="all" <?=$tp_all_selected?>>All Clicks</option>
			<option value="today" <?=$tp_today_selected?>>Today</option>
			<option value="yesterday" <?=$tp_yesterday_selected?>>Yesterday</option>
			<option value="thisweek" <?=$tp_thisweek_selected?>>This Week</option>
			<option value="lastweek" <?=$tp_lastweek_selected?>>Last Week</option>
			<option value="thismonth" <?=$tp_thismonth_selected?>>This Month</option>
			<option value="lastmonth" <?=$tp_lastmonth_selected?>>Last Month</option>
			<option value="thisyear" <?=$tp_thisyear_selected?>>This Year</option>
			<option value="lastyear" <?=$tp_lastyear_selected?>>Last Year</option>
			</select>
		</td>
		<td>
			<INPUT TYPE="submit" name="submit_top" value="Build Report -->" height="12" width="15" class="small">
		</td>
	</tr>
</table>
<br>

<!--FROM TO CONTROLS-->
<table width="580" border="0" cellpadding="0" cellspacing="0" align="center" bordercolor="#E0E0E0">
	<tr>
		<td align="center" valign="center">
		<font class="small">From:</font>
		<select name="fmonth" class="small">
		<?
			if (!$fmonth)
				$thismonth = date("n");
			else
				$thismonth = $fmonth;
			$months = array(1 => 'Jan', 'Feb', 'Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
			$i=1;
			foreach ($months as $month)
			{
				if ($thismonth == $i)
					echo "<option value=\"$i\" selected>$month</option>";	
				else
					echo "<option value=\"$i\">$month</option>";
				$i++;
			}
			if (!$fday)
				$today = date("j");
			else
				$today = $fday;
			if (!$fyear)
				$thisyear = date("Y");
			else
				$thisyear = $fyear;
		?>
		</select>
		<input type="text" name="fday" class="small" size="2" value="<?=$today?>">
		<input type="text" name="fyear" class="small" size="4" value="<?=$thisyear?>">
		
		<font class="small">&nbsp;&nbsp;&nbsp;&nbsp;To:</font>
		<select name="tmonth" class="small">
		<?
			if (!$tmonth)
				$thismonth = date("n");
			else
				$thismonth = $tmonth;							
			$i=1;
			foreach ($months as $month)
			{
				if ($thismonth == $i)
					echo "<option value=\"$i\" selected>$month</option>";	
				else
					echo "<option value=\"$i\">$month</option>";
				$i++;
			}
			if (!$tday)
				$today = date("j");
			else
				$today = $tday;
			if (!$tyear)
				$thisyear = date("Y");
			else
				$thisyear = $tyear;
		?>
		</select>
		<input type="text" name="tday" class="small" size="2" value="<?=$today?>">
		<input type="text" name="tyear" class="small" size="4" value="<?=$thisyear?>">

			<INPUT TYPE="submit" name="submit_bottom" value="Use Custom Time" height="12" width="15" class="small">
		</td>
	</tr>
</table>
</form>
<br><bR>


<?

//STEP 1: FILTER BY PURPOSE, GROUP
// all dynamic campaigns have purpose == all, group=dynamic
if ($purpose == "all purposes" && $group == "all")
	$campaigns = mysql_query("select * from adtrackz_campaigns");
elseif ($purpose == "all purposes" && $group != "all")
{
	if ($group == "default")
		$group = 0;
	$campaigns = mysql_query("select * from adtrackz_campaigns where groupID = '$group'");
}
elseif($purpose != "all purposes" && $group == "all")
	$campaigns = mysql_query("select * from adtrackz_campaigns where purpose = '$purpose'");
else
{
	$campaigns = mysql_query("select * from adtrackz_campaigns where  groupID = '$group' && purpose = '$purpose'");
}

//STEP 2: FILTER BY STATUS
// all dynamic campaigns are constantly running, so "all"
$now = date("Y-m-d H:m:s");
if ($status == "active")
{
	while($campaign1 = mysql_fetch_row($campaigns))
	{
		//if now is in between startdate and enddate
		if (earlier_date($now,$campaign1[5]) == $campaign1[5] && earlier_date($now,$campaign1[6]) == $now)
			$campaignIDs1[$campaign1[0]]=$campaign1[2];
	}
}
elseif ($status == "ended")
{
	while($campaign1 = mysql_fetch_row($campaigns))
	{
		// enddate is before now (campaign has ended)
		if (earlier_date($now,$campaign1[6]) == $campaign1[6])
			$campaignIDs1[$campaign1[0]]=$campaign1[2];
	}
}
elseif ($status == "pending")
{
	while($campaign1 = mysql_fetch_row($campaigns))
	{
		//now is before startdate (campaign hasn't started yet)
		if (earlier_date($now,$campaign1[5]) == $now)
			$campaignIDs1[$campaign1[0]]=$campaign1[2];
	}
}
elseif ($status == "all")
{
	while($campaign1 = mysql_fetch_row($campaigns))
		$campaignIDs1[$campaign1[0]]=$campaign1[2];
}


//STEP 3 - take out any split test campaigns
if ($campaignIDs1)
{
	foreach ($campaignIDs1 as $campaignID => $adcode)
	{
		//if campaign is not in list of split test campaigns, add it, otherwise, don't
		$st = mysql_fetch_row(mysql_query("select st from adtrackz_campaigns_st where campaignID='$campaignID'"));
		if (!$st[0])
			$campaignIDs[$campaignID] = $adcode;	
	}
}

//sort array 
if ($campaignIDs)
	asort($campaignIDs);

//sort by any column (create list of campaign IDs sorted by any column?
//that means we need the data for each row here, which we don't

//now we have our list of campaigns to display in the stats report
if ($campaignIDs)
{

	if ($submit_top)
	{

		//CONVERT TIME PERIOD INTO TIME STAMP
		if ($timeperiod == "all")
		{
			$from_timestamp = mktime (0,0,0,1,1,2004); 
			$to_timestamp = mktime (0,0,0,12,31,2014);  
		}
		elseif ($timeperiod == "today")
		{
			$from_timestamp = mktime (0,0,0,date("m"),date("d"),date("Y")); 
			$to_timestamp = mktime (23,59,59,date("m"),date("d"),date("Y")); 
		}
		elseif ($timeperiod == "yesterday")
		{
			$from_timestamp = mktime (0,0,0,date("m"),date("d")-1,date("Y")); 
			$to_timestamp = mktime (23,59,59,date("m"),date("d")-1,date("Y")); 
		}
		elseif ($timeperiod == "thisweek")
		{
		//0 (for Sunday) through 6 (for Saturday)
			$day_of_week = date("w");
			$from_timestamp = mktime (0,0,0,date("m"),date("d")-$day_of_week,date("Y")); 
			$to_timestamp = mktime (23,59,59,date("m"),date("d")+(6-$day_of_week),date("Y")); 
		}
		elseif ($timeperiod == "lastweek")
		{
			$day_of_week = date("w");
			$from_timestamp = mktime (0,0,0,date("m"),date("d")-(7+$day_of_week),date("Y")); 
			$to_timestamp = mktime (23,59,59,date("m"),date("d")-($day_of_week+1),date("Y")); 
		}
		elseif ($timeperiod == "thismonth")
		{
			$days_in_month = date("t");
			$from_timestamp = mktime (0,0,0,date("m"),01,date("Y")); 
			$to_timestamp = mktime (23,59,59,date("m"),$days_in_month,date("Y")); 
		}
		elseif ($timeperiod == "lastmonth")
		{
			$days_in_month = date("t");
			$from_timestamp = mktime (0,0,0,date("m")-1,01,date("Y")); 
			$to_timestamp = mktime (23,59,59,date("m")-1,$days_in_month,date("Y"));
		}
		elseif ($timeperiod == "thisyear")
		{
			$from_timestamp = mktime (0,0,0,01,01,date("Y")); 
			$to_timestamp = mktime (23,59,59,12,31,date("Y"));
		}
		elseif ($timeperiod == "lastyear")
		{
			$from_timestamp = mktime (0,0,0,01,01,date("Y")-1); 
			$to_timestamp = mktime (23,59,59,12,31,date("Y")-1);
		}
		else
			alert("invalid time period");	
	}
	elseif ($submit_bottom)
	{
		$from_timestamp = mktime (0,0,0,$fmonth,$fday,$fyear); 
		$to_timestamp = mktime (23,59,59,$tmonth,$tday,$tyear); 
	}

	if ($from_timestamp > $to_timestamp)
	{
		alert("The from time period you have chosen should be earlier than the to time period.");
		echo "<br>";
	}


	//fetch preferences data
	$pref = mysql_fetch_assoc(mysql_query("select * from adtrackz_preferences"));

	//THE MAIN STATS TABLE
	echo "<!--- THE MAIN STATS TABLE -->";
	echo "<table border=1 cellspacing=0 cellpadding=5 align=center>";
	echo "<tr bgcolor=#FA7F14 >";
	echo "<td class=tbhead2>Campaigns</td>";
	if ($pref['rawclicks'])
		echo "<td class=tbhead2>Raw Clicks</td>";
	if ($pref['clicks'])
		echo "<td class=tbhead2>Unique Clicks</td>";
	if ($pref['actions'])
		echo "<td class=tbhead2>Actions</td>";
	if ($pref['sales'])
		echo "<td class=tbhead2>Sales</td>";
	if ($pref['cta'])
		echo "<td class=tbhead2>CTA</td>";
	if ($pref['cts'])
		echo "<td class=tbhead2>CTS</td>";
	if ($pref['cpc'])
		echo "<td class=tbhead2>Avg CPC</td>";
	if ($pref['cpa'])
		echo "<td class=tbhead2>CPA</td>";
	if ($pref['cps'])
		echo "<td class=tbhead2>CPS</td>";
	if ($pref['cost'])
		echo "<td class=tbhead2>Cost</td>";
	if ($pref['revenue'])
		echo "<td class=tbhead2>Revenue</td>";
	if ($pref['profit'])
		echo "<td class=tbhead2>Profit</td>";
	if ($pref['roi'])
		echo "<td class=tbhead2>R.O.I.</td>";
	if ($pref['column_purpose'])
		echo "<td class=tbhead2>Purpose</td>";
	if ($pref['column_group'])
		echo "<td class=tbhead2>Group</td>";
	if ($pref['description'])
		echo "<td class=tbhead2>Description</td>";
	echo "</tr>";


	//MAIN STATS FOREACH LOOP - loop through each campaign
	 $c = 0; //to keep track of alternating rows for bg color
	foreach ($campaignIDs as $campaignID => $adcode1)
	{	
		//fetch campaign data for later use
		$campaign = mysql_fetch_assoc(mysql_query("select * from adtrackz_campaigns where ID='$campaignID'"));

		//affiliate tracking is the same as purpose=all for stats table
		if ($campaign['purpose'] == "affiliate")
			$campaign['purpose'] = "all";

		//get data for this campaign for this time period
		$rawclicks = get_campaign_data("rawclicks",$campaignID);
		$clicks = get_campaign_data("clicks",$campaignID);
		$actions = get_campaign_data("actions",$campaignID);
		$sales = get_campaign_data("sales",$campaignID);

		//get data for subcampaigns - using 2 dimensional array to store 
		$subcampaigns = mysql_query("select * from adtrackz_subcampaigns where campaignID='$campaignID' order by adcode asc");
		$subdata_flag = false; //if no subcampaigns, then make sure this is set to false
		while ($sub = mysql_fetch_assoc($subcampaigns))
		{
			$sub_adcode = $sub['adcode'];
			$subID = $sub['ID'];
			$subdata[$sub_adcode]['rawclicks'] = get_subcampaign_data("rawclicks",$campaignID, $subID);
			$subdata[$sub_adcode]['clicks'] = get_subcampaign_data("clicks",$campaignID, $subID);
			$subdata[$sub_adcode]['actions'] = get_subcampaign_data("actions",$campaignID, $subID);
			$subdata[$sub_adcode]['sales'] = get_subcampaign_data("sales",$campaignID, $subID);

			$sub_rawclicks = $subdata[$sub_adcode]['rawclicks'];
			$sub_clicks = $subdata[$sub_adcode]['clicks'];
			$sub_actions = $subdata[$sub_adcode]['actions'];
			$sub_sales = $subdata[$sub_adcode]['sales'];
			
			if ($sub_rawclicks || $sub_clicks || $sub_actions || $sub_sales)
				$subdata_flag = true;				
		}
		
		//if no activity in this campaign and no activity in it's subcampaigns for this time period, 
		//then don't display this campaign
		//get prefences
		// && pref = don't display 
		if (!$rawclicks && !$clicks && !$actions && !$sales && $subdata_flag === false && $pref['campaign_display'])
			continue;

		//CALCULATE COST
		if ($campaign['ppc'])
		{
			//true cost
			$cpc_data = mysql_fetch_row(mysql_query("select sum(cpc) from adtrackz_clicks where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp' && uniqueflag = 1"));
			//cost is sum of all clicks in this period, 
			//remember that in go.php if click doesn't have cpc set, then default cpc from campaign is used
			//therefore, cpc should always have a value
			$cost = $cpc_data[0];
		}
		elseif ($campaign['recurdays'] && $campaign['repeat']) 
		{
			//cost = from start date to now 
			$now = time();
			$startdate = strtotime($campaign['startdate']);

			//cycles so far, expressed in days
			$cycles = (($now - $startdate) / 86400) / $campaign['recurdays']; 
			if ($cycles > $campaign['repeat']) //user defines how many cycles
				$cycles = $campaign['repeat'];
			$cost = $cycles * $campaign['cost']; //abs cost is # of cycles * specified campaign cost				
		}
		else //normal cost
			$cost = $campaign['cost'];

		//CALCULATE VALUES - get rid of zeros
		$cta = (!$clicks ? 0 : $actions / $clicks * 100);	
		$cts = (!$clicks ? 0 : $sales / $clicks * 100);
		$cpc = (!$clicks ? 0 : $cost / $clicks);
		$cpa = (!$actions ? 0 : $cost / $actions);
		$cps = (!$sales ? 0 : $cost / $sales);
		$revdata = mysql_fetch_row(mysql_query("select sum(revenue) from adtrackz_sales where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		$rev = $revdata[0];
		$profit = $rev - $cost;
		//$roi = $revenue / $cost * 100	??
		$roi = (!$cost ? 0 : ($profit / $cost) * 100);

		//ADD TOTALS (before formatting values)
		$total_rawclicks += $rawclicks;
		$total_clicks += $clicks;
		$total_actions += $actions;
		$total_sales += $sales;
		$total_cta += $cta;
		$total_cts += $cts;
		$total_cpc += $cpc;
		$total_cpa += $cpa;
		$total_cps += $cps;
		$total_cost += $cost;
		$total_rev += $rev;
		$total_profit += $profit;
		$total_roi += $roi;
		//rows
		if ($cta)
			$total_rows['cta'] += 1; 
		if ($cts)
			$total_rows['cts'] += 1; 
		if ($cpc)
			$total_rows['cpc'] += 1; 
		if ($cpa)
			$total_rows['cpa'] += 1; 
		if ($cps)
			$total_rows['cps'] += 1; 
		if ($roi)
			$total_rows['roi'] += 1; 

		//FORMAT VALUES
		$rawclicks = number_format($rawclicks, 0);
		$clicks = number_format($clicks, 0);
		$actions = number_format($actions, 0);
		$sales = number_format($sales, 0);
		$cta = (!$cta ? 0 : number_format($cta, 2));
		$cts = (!$cts ? 0 : number_format($cts, 2));
		$cpc = (!$cpc ? 0 : number_format($cpc, 2));
		$cpa = (!$cpa ? 0 : number_format($cpa, 2));
		$cps = (!$cps ? 0 : number_format($cps, 2));
		$rev = (!$rev ? 0 : number_format($rev, 2));
		$cost = (!$cost ? 0 : number_format($cost, 2));
		$profit = (!$profit ? 0 : number_format($profit, 2));		
		$roi = (!$roi ? 0 : number_format($roi, 2));

		//SET STATUSPIC
		$now = date("Y-m-d H:i:s"); 
		if ((earlier_date ($campaign['startdate'], $now) == $campaign['startdate']) && (earlier_date ($campaign['enddate'], $now) == $now))
			$statuspic = "inprogress3.gif";
		elseif ((earlier_date ($campaign['startdate'], $now) == $campaign['startdate']) && (earlier_date ($campaign['enddate'], $now) == $campaign['enddate']))
			$statuspic = "ended3.gif";
		elseif (earlier_date ($campaign['startdate'], $now) == $now)
			$statuspic = "scheduled3.gif";

		//alternate bg colors between campaigns
		$c++;
		//need better colors
		if (!($c % 2))
			$tr = "<tr bgcolor=#F0F0F0>";
		else
			$tr = "<tr bgcolor=#d8d8d8>";

		//massage adcode to break at 30 char
		$wcampaign_adcode = wordwrap($campaign['adcode'],30,"<br>",1);

		echo $tr;
		echo '<td align="left"><table><tr><td valign=top><img src="'.$statuspic.'"></td><td><a href="dstats-summary.php?cID='.$campaign['ID'].'">'.$wcampaign_adcode.'</a></td></tr></table></td>';
		if ($pref['rawclicks'])
			echo "<td class=tb1>$rawclicks</td>";
		if ($pref['clicks'])
			echo "<td class=tb1>$clicks</td>";
		if ($pref['actions'])
			echo "<td class=tb1>$actions</td>";
		if ($pref['sales'])
			echo "<td class=tb1>$sales</td>";
		if ($pref['cta'])
			echo "<td class=tb1>$cta%</td>";
		if ($pref['cts'])
			echo "<td class=tb1>$cts%</td>";
		if ($pref['cpc'])
			echo "<td class=tb1>\$$cpc</td>";
		if ($pref['cpa'])
			echo "<td class=tb1>\$$cpa</td>";
		if ($pref['cps'])
			echo "<td class=tb1>\$$cps</td>";
		if ($pref['cost'])
			echo "<td class=tb1>\$$cost</td>";
		if ($pref['revenue'])
			echo "<td class=tb1>\$$rev</td>";
		if ($pref['profit'])
		{
			if ($profit < 0)
				echo "<td class=tb1><font color=#Ffffff>\$$profit</font></td>";
			else
				echo "<td class=tb1><font color=#FFFFFF>\$$profit</font></td>";
		}
		if ($pref['roi']) //but isn't roi technically negative when it's below 100%?
		{
			if ($roi < 0 ) 
				echo "<td class=tb1><font color=#Fffff>$roi%</font></td>";
			else
				echo "<td class=tb1><font color=#ffffff>$roi%</font></td>";
		}
		if ($pref['column_purpose'])
			echo "<td class=tb1>&nbsp;".$campaign['purpose']."</td>";
		if ($pref['column_group'])
		{			
			if (!$campaign['groupID'])
				echo "<td class=tb1>&nbsp;default</td>";
			else
			{
				$cgroup = mysql_fetch_row(mysql_query("select groupname from adtrackz_groups where ID='".$campaign['groupID']."'"));	
				echo "<td class=tb1>&nbsp;$cgroup[0]</td>";
			}
		}
		if ($pref['description'])
			echo "<td class=tb1>&nbsp;".$campaign['description']."</td>";				
		echo "</tr>";

		//LIST OF SUBCAMPAIGNS FOR THIS CAMPAIGN
		$subcampaigns = mysql_query("select * from adtrackz_subcampaigns where campaignID='$campaignID' order by adcode asc");
		while ($sub = mysql_fetch_assoc($subcampaigns))
		{
			$sub_adcode = $sub['adcode'];
			//get subcampaign data
			$sub_rawclicks = $subdata[$sub_adcode]['rawclicks'];
			$sub_clicks = $subdata[$sub_adcode]['clicks'];
			$sub_actions = $subdata[$sub_adcode]['actions'];
			$sub_sales = $subdata[$sub_adcode]['sales'];
			//if no data to display, skip it
			//get prefences
			// && pref = don't display 
			if (!$sub_rawclicks && !$sub_clicks && !$sub_actions && !$sub_sales && $pref['subcampaign_display'])
				continue;

			//CALCULATE COST
			if ($sub['ppc'])
			{
				$sub_cpc_data = mysql_fetch_row(mysql_query("select sum(cpc) from adtrackz_clicks where campaignID='$campaignID' && subID = ".$sub['ID']." && timest >= '$from_timestamp' && timest <= '$to_timestamp' && uniqueflag = 1"));
				//cost is sum of all clicks in this period, 
				//remember that in go.php if click doesn't have cpc set, then default cpc from campaign is used
				//therefore, cpc should always have a value
				$sub_cost = $sub_cpc_data[0];
			}
			else //normal cost
			{
				$sub_cost = $sub['cost'];
			}

			//CALCULATE OTHER VALUES - get rid of zeros
			$sub_cta = (!$sub_clicks ? 0 : $sub_actions / $sub_clicks * 100);	
			$sub_cts = (!$sub_clicks ? 0 : $sub_sales / $sub_clicks * 100);
			$sub_cpc = (!$sub_clicks ? 0 : $sub_cost / $sub_clicks);		
			$sub_cpa = (!$sub_actions ? 0 : $sub_cost / $sub_actions);
			$sub_cps = (!$sub_sales ? 0 : $sub_cost / $sub_sales);
			$sub_revdata = mysql_fetch_row(mysql_query("select sum(revenue) from adtrackz_sales where campaignID='$campaignID' && subID = ".$sub['ID']." && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
			$sub_rev = $sub_revdata[0];
			$sub_profit = $sub_rev - $sub_cost;
			//$roi = $revenue / $cost * 100	??
			$sub_roi = (!$sub_cost ? 0 : $sub_profit / $sub_cost * 100);

			//ADD TOTALS - (before formatting values for display)
			$total_rawclicks += $sub_rawclicks;
			$total_clicks += $sub_clicks;
			$total_actions += $sub_actions;
			$total_sales += $sub_sales;
			$total_cta += $sub_cta;
			$total_cts += $sub_cts;
			$total_cpc += $sub_cpc;
			$total_cpa += $sub_cpa;
			$total_cps += $sub_cps;
			$total_cost += $sub_cost;
			$total_rev += $sub_rev;
			$total_profit += $sub_profit;
			$total_roi += $sub_roi;
			//rows
			if ($sub_cta)
				$total_rows['cta'] += 1; 
			if ($sub_cts)
				$total_rows['cts'] += 1; 
			if ($sub_cpc)
				$total_rows['cpc'] += 1; 
			if ($sub_cpa)
				$total_rows['cpa'] += 1; 
			if ($sub_cps)
				$total_rows['cps'] += 1; 
			if ($sub_roi)
				$total_rows['roi'] += 1; 

			//FORMAT VALUES
			$sub_rawclicks = number_format($sub_rawclicks, 0);
			$sub_clicks = number_format($sub_clicks, 0);
			$sub_actions = number_format($sub_actions, 0);
			$sub_sales = number_format($sub_sales, 0);
			$sub_cta = (!$sub_cta ? 0 : number_format($sub_cta, 2));
			$sub_cts = (!$sub_cts ? 0 : number_format($sub_cts, 2));
			$sub_cpc = (!$sub_cpc ? 0 : number_format($sub_cpc, 2));
			$sub_cpa = (!$sub_cpa ? 0 : number_format($sub_cpa, 2));
			$sub_cps = (!$sub_cps ? 0 : number_format($sub_cps, 2));
			$sub_rev = (!$sub_rev ? 0 : number_format($sub_rev, 2));
			$sub_cost = (!$sub_cost ? 0 : number_format($sub_cost, 2));
			$sub_profit = (!$sub_profit ? 0 : number_format($sub_profit, 2));		
			$sub_roi = (!$sub_roi ? 0 : number_format($sub_roi, 2));
			//DISPLAY SUBCAMPAIGN ROW(do we need to * the actions if actions is not purpose of campaign?)
			//dstats-summary.php?cID='.$campaign[0].'&stats_select='.$s.'  <- um... this was 3.13 call to detailed stats sub
			if (!($c % 2))
				$tr = "<tr bgcolor=#F0F0F0>";
			else
				$tr = "<tr bgcolor=#d8d8d8>";
			echo $tr;

			//massage adcode, max 30 chars on one line						
			$separator = "<br><span style=margin:25pt;></span>";
			$wsub_adcode = wordwrap($sub['adcode'],30,$separator,1);
			
			echo '<td><span style=margin:25pt;><a href="dstats-summary.php?cID='.$campaign['ID'].'&sID='.$sub['ID'].'">'.$wsub_adcode.'</a></span></td>';
//			echo '<td><table><tr><td width=25>&nbsp;</td><td><a href="dstats-summary.php?cID='.$campaign['ID'].'&sID='.$sub['ID'].'">'.$wsub_adcode.'</a></td></tr></table></td>';
			if ($pref['rawclicks'])
				echo "<td class=tb1>$sub_rawclicks</td>";
			if ($pref['clicks'])
				echo "<td class=tb1>$sub_clicks</td>";
			if ($pref['actions'])
				echo "<td class=tb1>$sub_actions</td>";
			if ($pref['sales'])
				echo "<td class=tb1>$sub_sales</td>";
			if ($pref['cta'])
				echo "<td class=tb1>$sub_cta%</td>";
			if ($pref['cts'])
				echo "<td class=tb1>$sub_cts%</td>";
			if ($pref['cpc'])
				echo "<td class=tb1>\$$sub_cpc</td>";
			if ($pref['cpa'])
				echo "<td class=tb1>\$$sub_cpa</td>";
			if ($pref['cps'])
				echo "<td class=tb1>\$$sub_cps</td>";
			if ($pref['cost'])
				echo "<td class=tb1>\$$sub_cost</td>";
			if ($pref['revenue'])
				echo "<td class=tb1>\$$sub_rev</td>";
			if ($pref['profit'])
			{
				if ($sub_profit < 0)
					echo "<td class=tb1><font color=#F51800>\$$sub_profit</font></td>";
				else
					echo "<td class=tb1><font color=#0F87BE>\$$sub_profit</font></td>";
			}
			if ($pref['roi']) //but isn't roi technically negative when it's below 100%?
			{
				if ($sub_roi < 0 ) 
					echo "<td class=tb1><font color=#F51800>$sub_roi%</font></td>";
				else
					echo "<td class=tb1><font color=#FFFFFF>$sub_roi%</font></td>";
			}
			if ($pref['column_purpose'])
				echo "<td class=tb1>&nbsp;".$campaign['purpose']."</td>";
			if ($pref['column_group'])
			{			
				if (!$campaign['groupID'])
					echo "<td class=tb1>&nbsp;default</td>";
				else
				{
					$cgroup = mysql_fetch_row(mysql_query("select groupname from adtrackz_groups where ID='".$campaign['groupID']."'"));	
					echo "<td class=tb1>&nbsp;$cgroup[0]</td>";
				}
			}
			if ($pref['description'])
			{
				if ($sub['description'])
					echo "<td class=tb1>".$sub['description']."</td>";	
				else
					echo "<td class=tb1>&nbsp;</td>";	
			}
			echo "</tr>";

			unset ($sub_rawclicks, $sub_clicks, $sub_actions, $sub_sales, $sub_cta, $sub_cts, $sub_cpc, $sub_cpa, $sub_cps, $sub_cost, $sub_rev, $sub_profit, $sub_roi);
		}
		unset ($subdata_flag, $rawclicks, $clicks, $actions, $sales, $cta, $cts, $cpc, $cpa, $cps, $cost, $rev, $profit, $roi);
	} // end campaigns loop

	//CALCULATE TOTALS (get averages)
	//fix: may 5th
	//instead of taking average of rows, calculate in terms of other totals
	$total_cta = (!$total_clicks ? 0 : $total_actions / $total_clicks * 100);	
	$total_cts = (!$total_clicks ? 0 : $total_sales / $total_clicks * 100);
	$total_cpc = (!$total_clicks ? 0 : $total_cost / $total_clicks);
	$total_cpa = (!$total_actions ? 0 : $total_cost / $total_actions);
	$total_cps = (!$total_sales ? 0 : $total_cost / $total_sales);
	$total_roi = (!$total_cost ? 0 : ($total_profit / $total_cost) * 100);

	//FORMAT TOTALS
	$total_rawclicks = number_format($total_rawclicks, 0);
	$total_clicks = number_format($total_clicks, 0);
	$total_actions = number_format($total_actions, 0);
	$total_sales = number_format($total_sales, 0);
	$total_cta = (!$total_cta ? 0 : number_format($total_cta, 2));
	$total_cts = (!$total_cts ? 0 : number_format($total_cts, 2));
	$total_cpc = (!$total_cpc ? 0 : number_format($total_cpc, 2));
	$total_cpa = (!$total_cpa ? 0 : number_format($total_cpa, 2));
	$total_cps = (!$total_cps ? 0 : number_format($total_cps, 2));
	$total_rev = (!$total_rev ? 0 : number_format($total_rev, 2));
	$total_cost = (!$total_cost ? 0 : number_format($total_cost, 2));
	$total_profit = (!$total_profit ? 0 : number_format($total_profit, 2));		
	$total_roi = (!$total_roi ? 0 : number_format($total_roi, 2));

	//display totals row
	echo "<tr bgcolor=#FA7F14 >";
	echo '<td class=tbhead2>Total</th>';
	if ($pref['rawclicks'])
		echo "<td class=tbhead2>$total_rawclicks</td>";
	if ($pref['clicks'])
		echo "<td class=tbhead2>$total_clicks</td>";
	if ($pref['actions'])
		echo "<td class=tbhead2>$total_actions</td>";
	if ($pref['sales'])
		echo "<td class=tbhead2>$total_sales</td>";
	if ($pref['cta'])
		echo "<td class=tbhead2>$total_cta%</td>";
	if ($pref['cts'])
		echo "<td class=tbhead2>$total_cts%</td>";
	if ($pref['cpc'])
		echo "<td class=tbhead2>\$$total_cpc</td>";
	if ($pref['cpa'])
		echo "<td class=tbhead2>\$$total_cpa</td>";
	if ($pref['cps'])
		echo "<td class=tbhead2>\$$total_cps</td>";
	if ($pref['cost'])
		echo "<td class=tbhead2>\$$total_cost</td>";
	if ($pref['revenue'])
		echo "<td class=tbhead2>\$$total_rev</td>";
	if ($pref['profit'])
	{
		if ($total_profit < 0)
			echo "<td class=tbhead2><font color=#F51800>\$$total_profit</font></td>";
		else
			echo "<td class=tbhead2><font color=#FFFFFF>\$$total_profit</font></td>";
	}
	if ($pref['roi']) //but isn't roi technically negative when it's below 100%?
	{
		if ($total_roi < 0 ) 
			echo "<td class=tbhead2><font color=#F51800>$total_roi%</font></td>";
		else
			echo "<td class=tbhead2><font color=#FFFFFF>$total_roi%</font></td>";
	}
	if ($pref['column_purpose'])
		echo "<td class=tbhead2>&nbsp;</td>";
	if ($pref['column_group'])
		echo "<td class=tbhead2>&nbsp;</td>";
	if ($pref['description'])
		echo "<td class=tbhead2>&nbsp;</td>";
	echo "</tr>";
}
else //no campaigns from filters
	echo "<br><br><table><tr><td>There are no campaigns to display. Please try another group, status or time period.</td></tr>";

//the end
echo "</table><br><br>";


?>
<table align=center>
<tr>
	<td colspan=6 align=center><b>Campaign Status Legend:</b></td>
</tr>
<tr>
	</td><td>scheduled</td>	<td><img src=scheduled3.gif>
</tr><tr>
	<td>in progress</td>	<td><img src=inprogress3.gif></td>
</tr><tr>
	<td>ended</td>	<td><img src=ended3.gif></td>
</tr>
</table>

<?


require "footer.php";



//FUNCTIONS

function get_campaign_data($type,$campaignID)
{
	global $from_timestamp, $to_timestamp;

	if ($type == "rawclicks")
	{
		//RAWCLICKS
		$rawclickdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_clicks where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp'")); 
		return $rawclickdata[0];
	}
	elseif ($type == "clicks")
	{
		//CLICKS
		$clickdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_clicks where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp' && uniqueflag=1"));
		return $clickdata[0];
	}
	elseif ($type == "actions")
	{
		//CAMPAIGN ACTIONS
		$actiondata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_actions where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		return $actiondata[0];

	}
	elseif ($type == "sales")
	{
		//CAMPAIGN SALES
		$salesdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_sales where campaignID='$campaignID' && subID = 0 && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		return $salesdata[0];
	}
}

function get_subcampaign_data($type,$campaignID, $subID)
{
	global $from_timestamp, $to_timestamp;

	if ($type == "rawclicks")
	{
		//SUBCAMPAIGN CLICKS
		$sub_rawclicksdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_clicks where campaignID='$campaignID' && subID = '$subID' && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		return $sub_rawclicksdata[0];
	}
	elseif ($type == "clicks")
	{
		$sub_clicksdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_clicks where campaignID='$campaignID' && subID = '$subID' && timest >= '$from_timestamp' && timest <= '$to_timestamp' && uniqueflag=1"));
		return $sub_clicksdata[0];
	}
	elseif ($type == "actions")
	{
		//SUBCAMPAIGN ACTIONS
		$sub_actionsdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_actions where campaignID='$campaignID' && subID = '$subID' && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		return $sub_actionsdata[0];
	}
	elseif ($type == "sales")
	{
		//SUBCAMPAIGN SALES
		$sub_salesdata = mysql_fetch_row(mysql_query("select count(ID) from adtrackz_sales where campaignID='$campaignID' && subID = '$subID' && timest >= '$from_timestamp' && timest <= '$to_timestamp'"));
		return $sub_salesdata[0];
	}
}


?>